package util;

import java.sql.*;

public class DBUtil {
    static String url="jdbc:mysql:///companymanager?characterEncoding=utf8";
    static String user="root";
    static String pwd="xem314159";
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    public static Connection getCon() throws SQLException {
        Connection con = DriverManager.getConnection(url, user, pwd);
        return con;
    }
    public static ResultSet query(String sql, Object... keys) {
        ResultSet rs = null;
        try {
            Connection con = getCon();
            PreparedStatement pst = con.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i + 1), keys[i]);
            }
            rs = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static int update(String sql, Object... keys) {
        int rs = 0;
        try {
            Connection con = getCon();
            PreparedStatement pst = con.prepareStatement(sql);
            for (int i = 0; i < keys.length; i++) {
                pst.setObject((i + 1), keys[i]);
            }
            rs = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pst != null) {
                pst.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

}
